from socket import *
from multiprocessing import Process
import re

# 设置静态文件根目录
HTML_ROOT_DIR = "./html"


def handler(clientSocket):
	"""处理客户端请求"""
	# 获取客户端请求数据
	requestData = clientSocket.recv(1024)
	requestLines = requestData.splitlines()
	for line in requestLines:
		print(line)

	requestStartLine = requestLines[0]

	# 提取用户请求的文件名
	fileName = re.match(r"\w+\s+(/[^\s]*)\s", requestStartLine.decode('utf-8')).group(1)

	if fileName.endswith('.py'):
		pass
	else:
		if '/' == fileName:
			fileName = '/index.html'
			# 打开文件 读取内容
			try:
				file = open(HTML_ROOT_DIR + fileName, 'rb')
			except IOError:
				responseStartLine = 'HTTP/1.1 404 Not Found\r\n'
				responseBody = 'the file is not found'
			else:
				fileData = file.read()
				file.close()
				# 构造响应数据
				responseStartLine = "HTTP/1.1 200 OK\r\n"
				responseBody = fileData.decode('utf-8')

	responseHeaders = "Server: My Server\r\n"

	response = responseStartLine + responseHeaders + "\r\n" + responseBody
	print(response)
	# 向客户端返回响应数据
	clientSocket.send(bytes(response, 'utf-8'))
	# 关闭客户端
	clientSocket.close()


if __name__ == '__main__':
	serverSocket = socket(AF_INET, SOCK_STREAM)
	serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
	serverSocket.bind(('', 8080))
	serverSocket.listen(128)

while True:
	clientSocket, clientAddress = serverSocket.accept()
	print("[%s, %s] 用户连接上了" % clientAddress)
	# 拷贝了一份到子进程中去了
	handleClientProcess = Process(target=handler, args=(clientSocket,))
	handleClientProcess.start()
	clientSocket.close()
